How to Download a File from NodeJS Server using Express | 您所在的位置:网站首页 › How to Serve Static Files with Express and Nodejs › How to Download a File from NodeJS Server using Express |
Table Of Contents
1
Overview
2
Setting Up
3
Basic File Download
4
Serving Static Files
5
Streaming Large Files
6
Handling Errors
7
Conclusion
Overview
Node.js is a powerful platform for building network applications, and Express is a popular web framework for Node.js. Together, they can be used to serve and manage downloads of files of any type. In this tutorial, we’ll explore how to set up an Express server and implement routes that allow users to download files from a Node.js server. Throughout this guide, we will start with the basics, such as setting up a simple Express server and serving static files. Then, we’ll move on to more advanced concepts, such as streaming large files, handling errors, setting content headers, and securing file downloads with authentication middleware. Setting UpFirst, let’s create a new Node.js project and install Express: $ mkdir nodejs-file-download $ cd nodejs-file-download $ npm init -y $ npm install expressNow, set up a basic Express server in a file named app.js: const express = require('express'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Server running on port ${port}`); }); Basic File DownloadTo allow users to download a specific file, you can use the res.download() method provided by Express: const path = require('path'); app.get('/download', (req, res) => { const filePath = path.join(__dirname, 'files', 'example.pdf'); res.download(filePath); });Place the ‘example.pdf’ file inside a directory named ‘files’ in your project root. When users visit http://localhost:3000/download, they will be prompted to download ‘example.pdf’. Serving Static FilesExpress also has the ability to serve static files using the express.static middleware. To serve all files in a directory: app.use('/static', express.static('public'));The ‘public’ directory will now be statically served at the ‘/static’ route. Users can download files directly if they know the URL. Streaming Large FilesTo efficiently serve larger files, you can use streaming to prevent loading the entire file into memory: app.get('/stream', (req, res) => { const filePath = path.join(__dirname, 'files', 'large-video.mp4'); res.setHeader('Content-Disposition', 'attachment; filename=download.mp4'); const readStream = fs.createReadStream(filePath); readStream.pipe(res); });This route streams the ‘large-video.mp4’ file to the client as an attachment called ‘download.mp4’. Handling ErrorsWhen providing downloads, you should handle errors such as missing files or read errors: app.get('/download', (req, res) => { const filePath = path.join(__dirname, 'files', 'example.pdf'); res.download(filePath, (err) => { if (err) { if (!res.headersSent) { res.status(404).send('File not found'); } else { // Handle the error during streaming readStream.destroy(); res.end(); } } }); }); ConclusionIn conclusion, Node.js and Express make it simple to set up file downloads on a web server. Whether you are dealing with static file serving or streaming large files to the client with proper error handling, these tools offer a robust solution. By following the examples provided in this tutorial, you’ll be able to implement file download functionality in your own Node.js web application. Remember to always check and sanitize user inputs and consider using additional security measures like authentication and authorization when offering sensitive files for download. Happy coding! Next Article: How to Serve Static Files with Express and Node.js Previous Article: NodeJS + Pug: How to create reusable layouts (header, footer) Series: Node.js & Express Tutorials Node.js Related Articles NestJS File Upload Error – Multipart: Unexpected end of form NestJS: How to create cursor-based pagination (2 examples) Cursor-Based Pagination in SequelizeJS: Practical Examples MongooseJS: Cursor-Based Pagination Examples Node.js: How to get location from IP address (3 approaches) SequelizeJS: How to reset auto-increment ID after deleting records SequelizeJS: Grouping Results by Multiple Columns NestJS: Using Faker.js to populate database (for testing) NodeJS: Search and download images by keyword from Unsplash API NestJS: Generate N random users using Faker.js Sequelize Upsert: How to insert or update a record in one query NodeJS: Declaring types when using dotenv with TypeScript |
CopyRight 2018-2019 实验室设备网 版权所有 |